package bt.sim.grade;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bt.sim.student.Student;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;

public class GradeController extends Controller {

	public void read() {
		int page = getParaToInt("page");
		int rows = getParaToInt("rows");
		String gradeName = getPara("gradeName");
	
		Page<Grade> pagination = Grade.me.paginate(page, rows, gradeName);
		Map map = new HashMap();
		//按照easyui datagrid 数据封装格式进行二次封装
		map.put("rows", pagination.getList());
		map.put("total", pagination.getTotalRow());
		renderJson(map);
	}
	public void remove() {
		String delIds = getPara("delIds");
		Map<String, Object> result = new HashMap<String, Object>();
		
		String str[] = delIds.split(",");
		for(int i=0; i<str.length; i++) {
			Student student = Student.me.findFirst("select * from t_student where gradeId = ?", str[i]);
			if(student != null) {
				result.put("errorIndex", i);
				result.put("errorMsg", "班级下面有学生，不能删除！");
				renderJson(result);
				return;
			}
		}
		int delNums = Grade.me.gradeRemove(delIds);
		if(delNums > 0) {
			result.put("success", "true");
			result.put("delNums", delNums);
		} else {
			result.put("errorMsg", "删除失败！");
		}
		renderJson(result);
	}
	public void createOrUpdate() {
		
		Grade grade = getModel(Grade.class);
				
		boolean flag = false;
		if(grade.get("id") != null) {
			flag = grade.update();
		} else {
			flag = grade.save();
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		if(flag) {
			result.put("success", "true");
		} else {
			result.put("errorMsg", "保存失败！");
		}
		renderJson(result);
	}
	public void readById() {
		int id = getParaToInt("id", -1);//默认-1
		Grade grade = Grade.me.findById(id);
		setAttr("grade", grade);
		render("dlg.jsp");
	}
	public void readComboList() {
		List<Grade> grades = new ArrayList<Grade>();
		Grade grade = new Grade().set("id", "").set("gradeName", "请选择...");
		grades.add(grade);
		grades.addAll(Grade.me.find("select * from t_grade"));
		
		renderJson(grades);
	}
	
}
